<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="城市标签" prop="cityName">
        <el-select @change="getList" v-model="queryParams.cityName" placeholder="请选择">
          <el-option v-for="item in cityNameOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="区域名称" prop="areaId">
        <ApiSelect
          :params="{ pageNum: 1, pageSize: 9999, cityName: cityName }"
          v-model="queryParams.areaId"
          :api="selectState.areaList.api"
          :valueField="selectState.areaList.valueField"
          :labelField="selectState.areaList.labelField"
          :resultField="selectState.areaList.resultField"
          clearable
        />
      </el-form-item>
      <el-form-item label="线路名称" prop="routeId">
        <ApiSelect
          :params="{ areaId: queryParams.areaId, enable: 1 }"
          v-model="queryParams.routeId"
          :api="selectState.route.api"
          :valueField="selectState.route.valueField"
          :labelField="selectState.route.labelField"
          clearable
        />
      </el-form-item>
      <el-form-item label="点位名称" prop="positionId">
        <ApiSelect
          :params="{ routeId: queryParams.routeId, enable: 1 }"
          v-model="queryParams.positionId"
          :api="selectState.point.api"
          :valueField="selectState.point.valueField"
          :labelField="selectState.point.labelField"
          clearable
        />
      </el-form-item>
      <el-form-item label="设备名称" prop="machineName">
        <el-input
          style="width: 214px"
          v-model="queryParams.machineName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter="handleQuery(false)"
        />
      </el-form-item>
      <el-form-item label="设备编号" prop="machineId">
        <el-input
          style="width: 214px"
          v-model="queryParams.machineId"
          placeholder="请输入设备编号"
          clearable
          @keyup.enter="handleQuery(false)"
        />
      </el-form-item>
      <el-form-item>
        <div class="btn-group">
          <el-button
            plain
            v-hasPermi="['transactionData:transactionData:export']"
            @click="handleExport"
          >
            导出数据
          </el-button>

          <el-radio-group v-model="radioValue" @change="handleDateRange" style="flex-shrink: 0">
            <el-radio-button label="当天" />
            <el-radio-button label="最近7天" />
            <el-radio-button label="最近30天" />
          </el-radio-group>

          <el-date-picker
            v-model="daterange"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="dateChange"
            :clearable="false"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
          />
        </div>
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery(true)">重置</el-button>
        <el-button type="primary" @click="handleQuery(false)">查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList()"></right-toolbar>
    </el-row>

    <div>
      <h3>数据总览</h3>
      <div class="dataBox">
        <div class="dataItem" v-for="item in dataList" :key="item.key">
          <span class="title">{{ item.title }}</span>
          <span class="price">{{ item.value || '0.00' }}</span>
        </div>
      </div>
    </div>

    <el-table v-loading="loading" :data="list">
      <el-table-column label="点位名称" align="center" prop="positionName" />
      <el-table-column label="设备名称" align="center" prop="machineName" />
      <el-table-column label="设备编号" align="center" prop="machineId" />
      <el-table-column label="设备端销售额（元）" align="center" prop="machineSaleMoney" />
      <el-table-column label="小程序销售额（元）" align="center" prop="appSaleMoney" />
      <el-table-column label="总销售额（元）" align="center" prop="saleMoney" />
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>
<script setup>
import useGlobalStore from '@/store/modules/global'
import { useOrganApiConfig } from '@/hooks/service'
import { parseTime } from '@/utils/tools'
import { getTransactionDataListApi, postTransactionDataTotalApi } from '@/api/dataReport'

const globalStore = useGlobalStore()
const cityNameOptions = computed(() => globalStore.myCityList)
const { proxy } = getCurrentInstance()
const selectState = useOrganApiConfig()

const dataList = ref([
  { title: '总销售额（元）', value: 0, key: 'saleMoney' },
  { title: '设备端销售额（元）', value: 0, key: 'machineSaleMoney' },
  { title: '小程序销售额（元）', value: 0, key: 'appSaleMoney' }
])
const queryRef = ref()
const list = ref([])
const loading = ref(false)
const showSearch = ref(true)
const total = ref(0)
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  areaId: null,
  routeId: null,
  positionId: null,
  machineName: null,
  machineId: null,
  cityName: cityNameOptions.value[0],
  startTime: null,
  endTime: null
})
const cityName = computed(() => queryParams.value.cityName)
const now = new Date()
const daterange = ref([
  parseTime(new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0)),
  parseTime(new Date(), '{y}-{m}-{d}') + ' 23:59:59'
])
/***获取列表 */
function getList() {
  loading.value = true
  queryParams.value.startTime = daterange.value[0] ? daterange.value[0] : null
  queryParams.value.endTime = daterange.value[1] ? daterange.value[1] : null
  getTransactionDataListApi(queryParams.value)
    .then((res) => {
      console.log(res)
      loading.value = false
      list.value = res.rows || []
      total.value = res.total || 0
    })
    .catch((err) => {
      console.log(err)
      loading.value = false
    })

  postTransactionDataTotalApi(queryParams.value)
    .then((res) => {
      dataList.value.forEach((i) => {
        if (res?.data?.hasOwnProperty(i.key)) {
          i.value = res.data[i.key]
        } else {
          i.value = 0
        }
      })
      console.log(dataList.value)
    })
    .catch((err) => {
      console.log(err)
    })
}

/**查询 */
function handleQuery(type) {
  console.log(daterange.value[0], daterange.value[1])
  if (type) {
    queryRef.value.resetFields()
    daterange.value = [
      parseTime(new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0)),
      parseTime(new Date(), '{y}-{m}-{d}') + ' 23:59:59'
    ]
    radioValue.value = '当天'
    handleQuery(false)
  } else {
    queryParams.value.pageNum = 1
    getList()
  }
}
const radioValue = ref('当天')
const dateChange = () => {
  radioValue.value = ''
  handleQuery(false)
}
function handleDateRange(val) {
  const end = parseTime(new Date(), '{y}-{m}-{d}') + ' 23:59:59'
  const start = new Date()
  switch (val) {
    case '最近30天':
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 29)
      daterange.value = [parseTime(start, '{y}-{m}-{d}') + ' 00:00:00', end]
      break
    case '最近7天':
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 6)
      daterange.value = [parseTime(start, '{y}-{m}-{d}') + ' 00:00:00', end]
      break
    case '当天':
      daterange.value = [parseTime(start, '{y}-{m}-{d}') + ' 00:00:00', end]
      break
    default:
      break
  }
  handleQuery(false)
}
/**导出 */
function handleExport() {
  proxy.download(
    'operation/statistics/admin/dealDataList/derive',
    { ...queryParams.value },
    `交易数据${new Date().getTime()}.xlsx`
  )
}
getList()
</script>
<style lang="scss" scoped>
.dataBox {
  display: flex;
  justify-content: center;
  .dataItem {
    display: flex;
    flex-direction: column;
    align-items: left;
    justify-content: space-between;
    width: 300px;
    height: 120px;
    border: 2px solid #ccc;
    border-radius: 6px;
    padding: 20px;
    margin: 0 30px 30px;
    font-size: 20px;
    .price {
      font-size: 30px;
      font-weight: 600;
    }
  }
}
.btn-group {
  display: flex;
  align-items: center;
}
.el-radio-group {
  margin: 0 10px;
}
</style>
